package com.jzo2o.orders.manager.service.client;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.jzo2o.api.market.CouponApi;
import com.jzo2o.api.market.dto.request.CouponUseReqDTO;
import com.jzo2o.api.market.dto.response.AvailableCouponsResDTO;
import com.jzo2o.api.market.dto.response.CouponUseResDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 优惠卷熔断降级处理
 *
 * @author Zhy
 * @version 1.0
 * @date 2025-04-11 9:56
 */
@Component
@Slf4j
public class MarketClient {

	@Resource
	private CouponApi couponApi;

	/**
	 * 获取可用优惠卷列表
	 *
	 * @return:
	 * @param:
	 */
	@SentinelResource(value = "findCouponList", fallback = "findCouponListFallback", blockHandler = "findCouponListBlockHandler")
	public List<AvailableCouponsResDTO> findCouponList(BigDecimal totalAmount) {
		return couponApi.getAvailable(totalAmount);
	}

	/**
	 * 降级方法
	 *
	 * @return:
	 * @param:
	 */
	public List<AvailableCouponsResDTO> findCouponListFallback(BigDecimal totalAmount, Throwable t) {
		log.error("获取可用优惠卷列表失败，服务降级，返回默认值，错误信息：{}", t.getMessage());
		AvailableCouponsResDTO dto = new AvailableCouponsResDTO();
		dto.setId(-1L);
		return List.of(dto);
	}

	/**
	 * 熔断方法
	 *
	 * @return:
	 * @param:
	 */
	public List<AvailableCouponsResDTO> findCouponListBlockHandler(BigDecimal totalAmount, BlockException be) {
		log.error("获取可用优惠卷列表失败，服务熔断，返回默认值，错误信息：{}", be.getMessage());
		AvailableCouponsResDTO dto = new AvailableCouponsResDTO();
		dto.setId(-2L);
		return List.of(dto);
	}


	/**
	 * 优惠券使用，并返回优惠金额
	 *
	 * @return:
	 * @param:
	 */
	@SentinelResource(value = "useCoupon", fallback = "useCouponFallback", blockHandler = "useCouponBlockHandler")
	public CouponUseResDTO useCoupon(@RequestBody CouponUseReqDTO couponUseReqDTO) {
		return couponApi.use(couponUseReqDTO);
	}

	/**
	 * 降级方法
	 *
	 * @return:
	 * @param:
	 */
	public CouponUseResDTO useCouponFallback(CouponUseReqDTO couponUseReqDTO, Throwable t) {
		log.error("优惠券使用失败，服务降级，返回默认值，错误信息：{}", t.getMessage());
		CouponUseResDTO dto = new CouponUseResDTO();
		dto.setDiscountAmount(BigDecimal.valueOf(-1));
		return dto;
	}

	/**
	 * 熔断方法
	 *
	 * @return:
	 * @param:
	 */
	public CouponUseResDTO useCouponBlockHandler(CouponUseReqDTO couponUseReqDTO, BlockException be) {
		log.error("优惠券使用失败，服务熔断，返回默认值，错误信息：{}", be.getMessage());
		CouponUseResDTO dto = new CouponUseResDTO();
		dto.setDiscountAmount(BigDecimal.valueOf(-2));
		return dto;
	}

}
